import { useState, useCallback, useEffect, useMemo } from 'react';
import { message, Select } from 'antd';
import { getStaticDataList, getStaticGroupList } from '../../services';
import { useForm } from '@formily/react';
import './index.less';
import { Field } from '@formily/core';
import { golbalGetSystemMessageEffect } from '@inbiz/render';
import { getMessage } from '@inbiz/react';

type IProps = {
  emit?: (type: any, ...arg: any) => void;
  onChange?: Function;
  value?: string;
};

const SelectGroup = (props: IProps) => {
  // 数据组
  const [groupList, $groupList] = useState<any>([]);
  // 默认值
  const [defaultValue, $defaultValue] = useState<any>(null);

  const info: any = useForm();
  let appId = useMemo(() => {
    return info.appInfo.appId;
  }, [info]);

  useEffect(() => {
    getGroupList(appId);
    golbalGetSystemMessageEffect(info.appInfo,'zh-cn')
  }, [info,props.value]);

  // 获取字典分组列表
  const getGroupList = useCallback(
    (appId: string) => {
      getStaticGroupList(appId)
        .then((res) => {
          $groupList([...res]);
          if (props.value && props.value !== '') {
            $defaultValue(props.value);
          }
        })
        .catch(() => {
          $groupList([]);
          message.error(getMessage('EformStaticList.tips.failedToGetList'));
        });
    },
    [props.value],
  );

  // 向外保存选中值
  const onChange = (e: any) => {
    props.onChange && props.onChange(e);
    const field = info.query(/staticDataList$/).take() as Field;
    if (field) {
      field.value = e;
    }
  };

  return (
    <div className="setting-select-nav">
      <Select
        defaultValue={defaultValue}
        key={defaultValue}
        showSearch
        filterOption={(val, opt: any) => {
          let label = (opt?.children as string) || '';
          let status = label.includes(val);
          return Boolean(status);
        }}
        placeholder={getMessage('EformStaticList.tips.pleaseSelect')}
        onChange={onChange}
        allowClear
      >
        {groupList?.map((item: any) => {
          return (
            <Select.Option value={item.Key} key={item.Key}>
              {item.Name}
            </Select.Option>
          );
        })}
      </Select>
    </div>
  );
};

export default SelectGroup;
